package com.taotao.openapi2.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.validation.annotation.Valid;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Valid
@Slf4j
@Api(tags = "文件下载")
@Controller
@Mapping("/download")
public class FileDownloadController {


    @Mapping("down/f1")
    public DownloadedFile down() {
        InputStream stream = new ByteArrayInputStream("{code:1}".getBytes(StandardCharsets.UTF_8));

        //使用 InputStream 实例化
        return new DownloadedFile("text/json", stream, "test.json");
    }

    @Mapping("down/f2")
    public DownloadedFile down12() {
        byte[] bytes = "test".getBytes(StandardCharsets.UTF_8);

        //使用 byte[] 实例化
        return new DownloadedFile("text/json", bytes, "test.txt");

    }

    @Mapping("down/f3")
    public File down2() {
        return new File("...");
    }

    @Mapping("down/f4")
    public void down3(Context ctx) throws IOException {
        File file = new File("...");

        ctx.outputAsFile(file);
    }}
